<?php

// $Id$

require_once('tcms_attachment_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_attachment_dbc.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/ci/tcms_ci_mod_dbc.class.php');


class TCMS_Attachment_Upload extends Tangra_Class {
	public static function process_uploaded_file(DB_Connection $dbc,
													$file_properties,
													$uploads_dir,
													TCMS_Settings_Attachments_DBC $attachments_settings,
													$ci_id = 0,
													$current_user = 0
													) {

		$attachment_dbc = new TCMS_Attachment_DBC();
		$attachment_dbc->set_orig_filename($file_properties['name']);
		$attachment_dbc->save($dbc); // to get id

		$destination_filename = sprintf("%010s", $attachment_dbc->get_id());
		$attachment_dbc->set_filename($destination_filename);

		$attachment_file_orig_tmp = $file_properties['tmp_name'];
		$attachment_dbc->set_size(filesize($attachment_file_orig_tmp));

		$target_dir = tangra_normalize_path($uploads_dir).$attachments_settings->get_upload_path();
		$target_file = $target_dir.$destination_filename.'_'.$attachment_dbc->get_orig_filename();

		move_uploaded_file($attachment_file_orig_tmp, $target_file);

		$last_dot_pos = strrpos($file_properties['name'], '.');
		if ($last_dot_pos) {
			$original_extension = strtolower(substr($file_properties['name'], $last_dot_pos + 1));
		} else {
			$original_extension = '';
		}
		$attachment_dbc->set_extension($original_extension);
		$attachment_dbc->set_path($attachments_settings->get_upload_path());
		// actual save
		$attachment_dbc->save($dbc);
		if ($ci_id) {
			$ci_attachment = new TCMS_CI_Attachment_DBC();
			$ci_attachment->set_attachment($attachment_dbc->get_id());
			$ci_attachment->set_ci($ci_id);
			$ci_attachment->save($dbc);

			$mod = new TCMS_CI_Mod_DBC();
			$mod->set_ci($ci_id);
			$mod->set_modified_by($current_user);
			$mod->save($dbc);
		}
		$ret = $attachment_dbc->get_id();

		return $ret;
	}
}